package ai.zixing;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 获取IOC容器
 */
@Component
public class OrderHandleChainService/* implements ApplicationContextAware*/ {
    //    //保存责任链中的处理者
//    private List<OrderHandleIntercept> handleList = new ArrayList<>();
//    @Override
//    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//        //获取指定接口实现类,并按照sort进行排序,放入List
//        //getBeansOfType这个方法能返回一个接口的全部实现类（前提是所有实现类都必须由Spring IoC容器管理）
//        Map<String, OrderHandleIntercept> serviceMap = applicationContext.getBeansOfType(OrderHandleIntercept.class);
//
//        handleList = serviceMap.values().stream()
//                .sorted(Comparator.comparing(OrderHandleIntercept::sort))
//                .collect(Collectors.toList());
//
//    }
//保存责任链中的处理者
    @Resource
    private List<OrderHandleIntercept> handleList;
    /**
     * 执行处理
     */
    public OrderContext execute(OrderContext context) {
        for (OrderHandleIntercept handleIntercept : handleList) {
            context = handleIntercept.handle(context);
        }

        return context;
    }
}
